import {
  Button,
  Space,
  InputNumber,
  Card,
  Form,
  Input,
  Radio,
  Select,
  DatePicker,
  Divider,
  App,
  Popconfirm,
  Drawer,
  Image,
  Alert
} from 'antd'
import { PageContainer, ProTable } from '@ant-design/pro-components'
import styles from './Coupon.less'
import { useEffect, useState, useRef } from 'react'
import { useModel, useSearchParams, history } from '@umijs/max'
import dayjs from 'dayjs'

const { RangePicker } = DatePicker

const extensionOptions = [
  {
    label: '自动推广',
    value: 1
  },
  {
    label: '私域推广',
    value: 2
  }
]

const discountsOptions = [
  {
    label: '下单立减',
    value: 1
  }
]

const CouponDetail = () => {
  const { CouponDetail, AddCoupon, UpdateCoupon, PlatformGoodsList, GetShipTypes } = useModel('Coupon')
  const { GetShopSelections, GetShowPlts } = useModel('Goods')

  const { message } = App.useApp()

  const [searchParams] = useSearchParams()
  const [addAndEditFormRef] = Form.useForm()
  const selectGoodsTableRef = useRef()

  const [currentId, setCurrentId] = useState(null) // 当前 id
  const [currentType, setCurrentType] = useState(null) // 当前 type
  const [isDisabled, setIsDisabled] = useState(false) // 当前 type
  const [initialValues, setInitialValues] = useState({
    show_type: 1,
    deduct_type: 1,
    content_type: 1,
    suite_goods_type: 2,
    receive_type: 1
  })

  const [shopList, setShopList] = useState([])
  const [shipList, setShipList] = useState([])
  const [goodsDrawerFlag, setGoodsDrawerFlag] = useState(false)
  const [drawerSelectGoods, setDrawerSelectGoods] = useState(null)
  const [searchChannel, setSearchChannel] = useState([])

  const selectGoodsColumns = [
    {
      title: '商品名称',
      dataIndex: 'goods_name',
      width: 200,
      render: (text, record) => (
        <Space>
          <Image width={48} src={record.goods_cover_url} />
          <a onClick={() => goProduct(3, record.id, record.merchant_id)}>{text}</a>
        </Space>
      )
    },
    {
      title: '商品ID',
      dataIndex: 'id',
      width: 60,
      hideInTable: true
    },
    {
      title: '买断价',
      dataIndex: 'buyout_price_range',
      hideInSearch: true,
      width: 140
    },
    {
      title: '租赁信息',
      dataIndex: 'rent_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('rent')) {
          const { deposit, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                押金：{deposit[0]}~{deposit[1]}
              </div>
              <div>
                租期：{periods[0]}~{periods[1]}
              </div>
              <div>
                期数：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                每期租金：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '买卖信息',
      dataIndex: 'buy_meal_info',
      hideInSearch: true,
      width: 300,
      render: (text, record) => {
        const { use_scope } = record
        if (use_scope && use_scope.includes('buy')) {
          const { first_pay_range, lease_terms, per_rent_range, periods } = text
          return (
            <>
              <div>
                首付款：{first_pay_range[0]}~{first_pay_range[1]}
              </div>
              <div>
                尾期：{lease_terms[0]}~{lease_terms[1]}
              </div>
              <div>
                期数：{periods[0]}~{periods[1]}
              </div>
              <div>
                每期尾款：{per_rent_range[0]}~{per_rent_range[1]}
              </div>
            </>
          )
        } else {
          return '/'
        }
      }
    },
    {
      title: '物流配送',
      dataIndex: 'delivery_type_names',
      width: 120,
      hideInSearch: true,
      render: text => (
        <>
          {text.map(i => (
            <div key={i} className={styles.delivery_name}>
              {i}
            </div>
          ))}
        </>
      )
    },
    {
      title: '归属店铺',
      dataIndex: 'shop_name',
      valueType: 'select',
      valueEnum: new Map(shopList),
      width: 120
    },
    {
      title: '物流配送',
      dataIndex: 'ship_type',
      hideInTable: true,
      valueType: 'select',
      valueEnum: new Map(shipList),
      width: 120
    },
    {
      title: '展示渠道',
      width: 100,
      dataIndex: 'plts',
      hideInSearch: true,
      valueType: 'select',
      valueEnum: new Map(searchChannel),
      // fieldProps: {
      //   mode: 'multiple'
      // },
      render: (text, record) => record.plts.map((i, index) => <div key={index}>{i}</div>)
    },
    {
      title: '提交时间',
      dataIndex: 'create_time',
      hideInSearch: true,
      width: 220
    },
    {
      title: '商品详情',
      key: 'option',
      width: 80,
      valueType: 'option',
      fixed: 'right',
      render: (_, row, index, action) => {
        return (
          <a
            key='check'
            onClick={() => {
              goProduct(3, row.id, row.merchant_id)
            }}
          >
            查看详情
          </a>
        )
      }
    }
  ]

  useEffect(() => {
    let id = searchParams.get('id')
    let type = searchParams.get('type')

    setCurrentId(id)
    setCurrentType(type)
    setIsDisabled(type !== 'add' && type !== 'edit')

    if (type !== 'add') {
      getDetailsInfo(id)
    }

    getShipSelection()
    getShopList()
    getDisplayChannels()
  }, [])

  // 获取展示渠道
  const getDisplayChannels = async () => {
    const res = await GetShowPlts()
    if (res) {
      let arr = []
      for (const resKey in res) {
        arr.push({
          id: resKey,
          value: res[resKey]
        })
      }
      arr && setSearchChannel(arr.map(i => [i.id, i.value]))
    }
  }

  const getShipSelection = async () => {
    let res = await GetShipTypes()
    if (res) {
      setShipList(res.map(i => [i.key, i.value]))
    }
    // selectGoodsTableRef
  }

  //  获取店铺列表
  const getShopList = async () => {
    const res = await GetShopSelections()
    setShopList(res.map(i => [i.id, i.shop_name]))
  }

  // 跳转商品页
  const goProduct = (type, id, merchant_id) => {
    let url = `/product?type=${type}&id=${id}&merchant_id=${merchant_id}`
    window.open(url)
  }

  // 获取详情
  const getDetailsInfo = async id => {
    const res = await CouponDetail({ id })
    if (res) {
      let data = res
      const formData = {
        ...data,
        use_at: [dayjs(data.use_start_at), dayjs(data.use_end_at)],
        show_at: dayjs(data.show_at)
      }
      if (data.content_type === 1) {
        formData.deduct_to = data.deduct_money
      } else {
        formData.deduct_amount = data.deduct_money
      }
      setDrawerSelectGoods(data.goods_ids)
      setInitialValues(formData)
      addAndEditFormRef.setFieldsValue(formData)
    }
  }

  const handleSubmit = async values => {
    let params = {
      ...values,
      deduct_money: values.content_type === 1 ? values.deduct_to : values.deduct_amount,
      use_start_at: dayjs(values.use_at[0]).format('YYYY-MM-DD HH:mm:ss'),
      use_end_at: dayjs(values.use_at[1]).format('YYYY-MM-DD HH:mm:ss'),
      show_at: dayjs(values.show_at).format('YYYY-MM-DD HH:mm:ss')
    }

    let res = null
    if (currentType === 'add') {
      res = await AddCoupon(params)
    } else if (currentType === 'edit') {
      res = await UpdateCoupon({ ...params, id: currentId })
    }

    if (res) {
      message.success('操作成功')
      window.close()
    }
  }

  const triggerGoodsDrawer = () => {
    setGoodsDrawerFlag(!goodsDrawerFlag)
  }

  const formatExtra = () => {
    return currentType === 'check'
      ? [
          <Popconfirm
            title='你确认关闭当前页面吗？'
            onConfirm={() => window.close()}
            okText='确认'
            cancelText='取消'
            key='cancel'
          >
            <Button>关闭</Button>
          </Popconfirm>,
          <Button
            key='edit'
            onClick={() => {
              history.push(`/couponDetail?type=edit&id=${currentId}`)
              setIsDisabled(false)
              setCurrentType('edit')
            }}
          >
            编辑
          </Button>
        ]
      : [
          <Popconfirm
            title='你确认取消吗？'
            onConfirm={() => addAndEditFormRef.resetFields()}
            okText='确认'
            cancelText='取消'
            key='cancel'
          >
            <Button>取消</Button>
          </Popconfirm>,
          <Popconfirm
            title='你确认保存吗？'
            onConfirm={() => {
              console.log('submit', addAndEditFormRef.getFieldsValue())
              addAndEditFormRef.submit()
            }}
            okText='确认'
            cancelText='取消'
            key='save'
          >
            <Button type='primary'>保存</Button>
          </Popconfirm>
        ]
  }

  const handleChangeSelectGoods = value => {
    if (isDisabled) {
      return
    }
    addAndEditFormRef.setFieldValue('goods_ids', value)
    setDrawerSelectGoods(value)
  }

  const disabledUseableDate = (current, { from }) => {
    if (currentType === 'add') {
      const diffDate = addAndEditFormRef.getFieldValue('show_at')
      if (from) {
        return (
          Math.abs(current.diff(from, 'days')) >= 60 ||
          (diffDate ? current <= diffDate : current < dayjs().startOf('day'))
        )
      }
      return diffDate ? current <= diffDate : current < dayjs().startOf('day')
    } else {
      const diffDate = addAndEditFormRef.getFieldValue('use_at')[1]
      console.log('diffDate', diffDate, current)
      // return current < diffDate
    }
  }

  const disabledShowDate = (current, { from }) => {
    const diffDate = addAndEditFormRef.getFieldValue('use_at')
    return diffDate && diffDate[0]
      ? current > diffDate[0] || current < dayjs().startOf('day')
      : current < dayjs().startOf('day')
  }

  return (
    <div className={styles.merchant_details}>
      <PageContainer
        header={{
          fixedHeader: true,
          title: (
            <div className={styles.header_title}>
              <span>{currentType === 'add' ? '添加优惠券' : '编辑优惠券'}</span>
              <Divider type='vertical' />
              <span className={styles.header_desc}>{currentType === 'add' ? '新增' : '编辑'}优惠券信息配置页</span>
            </div>
          ),
          extra: formatExtra()
        }}
      >
        <Form
          preserve={false}
          form={addAndEditFormRef}
          name='addAndEdit'
          initialValues={initialValues}
          scrollToFirstError
          disabled={isDisabled}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 10 }}
          onFinish={values => handleSubmit(values)}
        >
          <Card title='基础信息' bordered={false} style={{ marginBottom: 20 }}>
            <Form.Item
              name='show_type'
              label='推广方式'
              rules={[{ required: true, message: '请选择推广方式' }]}
              help='公域私域全链路自动透出，促进成交'
            >
              <Select placeholder='请选择' options={extensionOptions}></Select>
            </Form.Item>

            <Form.Item name='coupon_name' label='优惠券名称' rules={[{ required: true, message: '请输入优惠券名称' }]}>
              <Input placeholder='请输入' allowClear />
            </Form.Item>

            <Form.Item name='use_at' label='可用时间' rules={[{ required: true, message: '请输入可用时间' }]}>
              <RangePicker
                allowEmpty={currentType === 'edit' ? [true, true] : [false, false]}
                disabled={isDisabled ? [true, true] : currentType === 'edit' ? [true, false] : [false, false]}
                disabledDate={disabledUseableDate}
                minDate={initialValues.use_at?.[1]}
              ></RangePicker>
            </Form.Item>

            <Form.Item name='show_at' label='开始透出时间' rules={[{ required: true, message: '请输入开始透出时间' }]}>
              <DatePicker disabledDate={disabledShowDate}></DatePicker>
            </Form.Item>
          </Card>

          <Card title='优惠信息' style={{ marginBottom: 20 }}>
            <Form.Item
              name='deduct_type'
              label='优惠类型'
              rules={[{ required: true, message: '请选择优惠类型' }]}
              help='用户在下单时可以使用的优惠券，优惠减少的金额在总租金中扣除'
            >
              <Select placeholder='请选择' options={discountsOptions}></Select>
            </Form.Item>

            <Form.Item name='content_type' label='优惠内容' rules={[{ required: true, message: '请选择优惠内容' }]}>
              <Radio.Group>
                <Radio value={1} style={{ marginBottom: '10px' }}>
                  <Space>
                    无门槛，首期立减到
                    <Form.Item
                      noStyle
                      shouldUpdate={(prevValues, curValues) => prevValues.content_type !== curValues.content_type}
                    >
                      {() => {
                        const contentType = addAndEditFormRef.getFieldValue('content_type')
                        return (
                          <Form.Item
                            noStyle
                            name='deduct_to'
                            rules={contentType === 1 ? [{ required: true, message: '请输入首期立减到金额' }] : []}
                          >
                            <InputNumber
                              placeholder='请输入'
                              disabled={isDisabled || contentType !== 1}
                              precision={0}
                              min={0}
                              addonAfter='元'
                            />
                          </Form.Item>
                        )
                      }}
                    </Form.Item>
                  </Space>
                </Radio>
                <Radio value={2}>
                  <Space>
                    无门槛，下单减免
                    <Form.Item
                      noStyle
                      shouldUpdate={(prevValues, curValues) => prevValues.content_type !== curValues.content_type}
                    >
                      {() => {
                        const contentType = addAndEditFormRef.getFieldValue('content_type')
                        return (
                          <Form.Item
                            noStyle
                            name='deduct_amount'
                            rules={contentType === 2 ? [{ required: true, message: '请输入下单减免金额' }] : []}
                          >
                            <InputNumber
                              placeholder='请输入'
                              disabled={isDisabled || contentType !== 2}
                              precision={0}
                              min={0}
                              addonAfter='元'
                            />
                          </Form.Item>
                        )
                      }}
                    </Form.Item>
                  </Space>
                </Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              name='send_num'
              label='发放总量'
              rules={[{ required: true, message: '请输入发放总量' }]}
              help='修改优惠券总量时只能增加不能减少，请谨慎设置。'
            >
              <InputNumber placeholder='请输入' precision={0} min={0} addonAfter='张' />
            </Form.Item>

            <Form.Item
              name='suite_goods_type'
              label='适用商品'
              rules={[{ required: true, message: '请选择适用商品类型' }]}
            >
              <Radio.Group>
                <Radio value={1}>全部商品可用</Radio>
                <Radio value={2}>指定商品可用</Radio>
                <Radio value={3}>指定商品不可用</Radio>
              </Radio.Group>
            </Form.Item>

            <Form.Item
              noStyle
              shouldUpdate={(prevValues, curValues) => prevValues.suite_goods_type !== curValues.suite_goods_type}
            >
              {() => {
                const suiteGoodsType = addAndEditFormRef.getFieldValue('suite_goods_type')
                return suiteGoodsType === 1 ? null : (
                  <Form.Item
                    label=' '
                    name='goods_ids'
                    rules={[{ required: true, message: '请选择适用商品' }]}
                    colon={false}
                  >
                    <Button disabled={false} onClick={triggerGoodsDrawer}>
                      查看商品
                    </Button>
                    <span style={{ marginLeft: '8px' }}>
                      (已选<a onClick={triggerGoodsDrawer}>{drawerSelectGoods ? drawerSelectGoods.length : 0}</a>)
                    </span>
                  </Form.Item>
                )
              }}
            </Form.Item>
          </Card>

          <Card title='发放和使用规则' style={{ marginBottom: 20 }}>
            <Form.Item name='receive_type' label='领取规则' rules={[{ required: true, message: '请选择领取规则' }]}>
              <Radio.Group
              //  onChange={(e) => { if (e.target.value !== 2) { addAndEditFormRef.setFieldValue('limit_num', 0) } }}
              >
                <Radio value={1}>每人领取数量不限</Radio>
                <Radio value={2}>
                  <Space>
                    每人最多可领
                    <Form.Item
                      noStyle
                      shouldUpdate={(prevValues, curValues) => prevValues.receive_type !== curValues.receive_type}
                    >
                      {() => {
                        const receiveType = addAndEditFormRef.getFieldValue('receive_type')
                        return (
                          <Form.Item
                            noStyle
                            name='limit_num'
                            rules={receiveType === 2 ? [{ required: true, message: '请输入每人最多可领数量' }] : []}
                          >
                            <InputNumber
                              placeholder='请输入'
                              disabled={isDisabled || receiveType !== 2}
                              precision={0}
                              min={0}
                              addonAfter='张'
                            />
                          </Form.Item>
                        )
                      }}
                    </Form.Item>
                  </Space>
                </Radio>
              </Radio.Group>
            </Form.Item>
          </Card>
        </Form>
      </PageContainer>
      {/*添加商品抽屉*/}
      <Drawer
        title='选择商品'
        placement='right'
        className={styles.goods_drawer_wrapper}
        onClose={triggerGoodsDrawer}
        open={goodsDrawerFlag}
        width={980}
        destroyOnClose
        footer={
          <div className={styles.drawer_footer}>
            <Space>
              <div>已选商品：{drawerSelectGoods ? drawerSelectGoods.length : 0}</div>
              <Button
                onClick={() => {
                  setDrawerSelectGoods(null)
                  addAndEditFormRef.setFieldValue('goods_ids', null)
                  triggerGoodsDrawer()
                }}
              >
                取消
              </Button>
              <Button
                type='primary'
                disabled={!drawerSelectGoods || !drawerSelectGoods.length}
                onClick={triggerGoodsDrawer}
              >
                确认
              </Button>
            </Space>
          </div>
        }
      >
        <Alert message='仅可以选择展示中的商品。' type='info' showIcon />
        <ProTable
          search={{
            defaultCollapsed: false,
            labelWidth: 75,
            span: 6
          }}
          actionRef={selectGoodsTableRef}
          rowSelection={{
            selectedRowKeys: drawerSelectGoods || [],
            onChange: handleChangeSelectGoods
          }}
          request={async params => {
            const param = {
              is_display: 1,

              page: params.current,
              page_size: params.pageSize,
              goods_name: params.goods_name,
              id: params.id,
              merchant_id: params.shop_name,
              ship_type: params.ship_type
            }
            const res = await PlatformGoodsList(param)
            // setAddGoodsPageSize(params.pageSize)
            return {
              data: res.data,
              success: true,
              total: res.total
            }
          }}
          pagination={{
            pageSize: 10
            // pageSize: addGoodsPageSize
          }}
          options={false}
          rowKey='id'
          columns={selectGoodsColumns}
        />
      </Drawer>
    </div>
  )
}

export default CouponDetail
